package traveler.activities;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import traveler.controllers.GoogleMapsController;
import traveler.models.Step;
import traveler.tools.MapOverlay;
import traveler.tools.OverlayItems;
import traveler.tools.Road;
import traveler.tools.RoadProvider;
import traveler.activities.R;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.MyLocationOverlay;

public class GoogleMapsActivity extends MapActivity
{
	private GoogleMapsController _controller;
	private MyLocationOverlay _myLocation;
	private Road _road;
	private Handler _handler;
	private List<Overlay> _mapOverlays;
	private GeoPoint _geoPoint;
	
	@Override
    public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_maps);
		
		Bundle bundle = getIntent().getExtras();

        Drawable drawable = this.getResources().getDrawable(R.drawable.google_maps_marker);
		OverlayItems overlayItems = new OverlayItems(drawable);

		final MapView mapView = (MapView) findViewById(R.id.mapview);
		final MapController mapController = mapView.getController();
        mapView.setBuiltInZoomControls(true);
    	mapController.setZoom(13);
        
		if(bundle != null)
			_geoPoint = new GeoPoint(bundle.getInt(GoogleMapsController.LATITUDE), bundle.getInt(GoogleMapsController.LONGITUDE));
		
		_controller = new GoogleMapsController(this, mapController);
		_mapOverlays = mapView.getOverlays();
		
        enableGPS();
        
        LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, _controller);
        
        if(_geoPoint != null)
        {
        	overlayItems.addOverlay(new OverlayItem(_geoPoint, "My position", "My position"));
	        _mapOverlays.add(overlayItems);
	        
	        _handler = new Handler()
	        {
	            public void handleMessage(Message msg)
	            {
	            	_mapOverlays.add(new MapOverlay(_road, mapView));
	                mapView.invalidate();
	            };
	        };
        }
        
        _myLocation = new MyLocationOverlay(getApplicationContext(), mapView); 
        _myLocation.runOnFirstFix(new Runnable()
        {
    	    public void run()
    	    {
    	    	mapController.animateTo(_myLocation.getMyLocation());
    	    	
    	    	if(_geoPoint != null)
    	    		drawRoad();
    	    }
    	});
        
        if(_geoPoint != null)
        {
	        new Thread()
	        {
	        	@Override
	        	public void run()
	        	{
	        		drawRoad();
	        	}
	        }.start();
        }

		mapView.getOverlays().add(_myLocation);
	}
	
	private void enableGPS()
	{
	    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

	    if(provider.contains("gps"))
	        return;

	    Intent poke = new Intent();
	    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
	    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
	    poke.setData(Uri.parse("3"));
	    sendBroadcast(poke);
	}

	private InputStream getConnection(String url)
	{
		InputStream inputStream = null;
		
		try
		{
			URLConnection conn = new URL(url).openConnection();
			inputStream = conn.getInputStream();
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		return inputStream;
	}
	
	private void drawRoad()
	{
		if(_myLocation != null && _myLocation.isMyLocationEnabled())
		{
			Log.i("lat", _myLocation.getMyLocation() + "");
			Log.i("lat 1e6", _myLocation.getMyLocation().getLatitudeE6() / 1e6 + "");
			double fromLat = (double)_myLocation.getMyLocation().getLatitudeE6() / 1e6;
			double fromLon = (double)_myLocation.getMyLocation().getLongitudeE6() / 1e6;
			double toLat = Step.PARIS.getLatitudeE6() / 1e6;
			double toLon = Step.PARIS.getLongitudeE6() / 1e6;
			
			String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
			InputStream inputStream = getConnection(url);
			_road = RoadProvider.getRoute(inputStream);
			_handler.sendEmptyMessage(0);
		}
	}
	
	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}
	
	protected void onResume()
	{
		super.onResume();
		_myLocation.enableMyLocation();
	}
}
